﻿using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using NetFramework.Configuration;
using NetFramework.Collection;

namespace NetFramework.Web.Configuration
{
    /// <summary>
    /// 
    /// </summary>
    [ConfigFile("Configs/Resources/Css/*.config")]
	[XmlRoot("cssConfig")]
    public class CssConfig
    {
		private KeyedCollection<CssMapping> cssMappings;
		private SharedCssGroups sharedCssGroups;
		private PrivateCssGroups cssGroup;

        /// <summary>
        /// 
        /// </summary>
        [XmlArray("cssMappings")]
		[XmlArrayItem("add")]
		public KeyedCollection<CssMapping> CssMappings 
        {
			get { return cssMappings; }
			set { cssMappings = value; }
        }

		/// <summary>
		/// 
		/// </summary>
		[XmlElement("sharedCssGroups")]
		public SharedCssGroups SharedCssGroups
		{
			get { return sharedCssGroups; }
			set { sharedCssGroups = value; }
		}

		/// <summary>
		/// 
		/// </summary>
		[XmlArray("privateCssGroups")]
		[XmlArrayItem("cssGroup")]
		public PrivateCssGroups CssGroups
		{
			get { return cssGroup; }
			set { cssGroup = value; }
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="cssName"></param>
		/// <returns></returns>
		public CssMapping GetCss(string cssName)
		{
			return CssMappings[cssName];
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="pageName"></param>
		/// <returns></returns>
		public List<CssMapping> GetCssListInPage(string pageName)
		{
			List<CssMapping> cssMappingList = new List<CssMapping>();

			PrivateCssGroup mappingGroup = CssGroups.GetPrivateCssGroup(pageName);
			if (mappingGroup != null)
			{
				SharedCssGroup sharedCssGroup = null;
				// 处理Shared Css
                if (!string.IsNullOrEmpty(mappingGroup.SharedCssGroup))
				{
                    sharedCssGroup = SharedCssGroups.GetCssGroup(mappingGroup.SharedCssGroup);
				}
				else
				{
					sharedCssGroup = SharedCssGroups.DefaultCssGroup;
				}

				if (sharedCssGroup != null)
				{
					AddCss(cssMappingList, sharedCssGroup.CssNames);
				}

				// 处理Private Css
				AddCss(cssMappingList, mappingGroup.CssNames);
			}

			cssMappingList.Sort(delegate(CssMapping x, CssMapping y){
                return x.Order.CompareTo(y.Order);
            });

			return cssMappingList;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="cssMappingList"></param>
		/// <param name="cssNames"></param>
		private void AddCss(List<CssMapping> cssMappingList, params string[] cssNames)
		{
			if (cssNames == null)
				return;

			foreach (string cssName in cssNames)
			{
				CssMapping cssMapping = cssMappings[cssName];
				if (cssMapping != null && cssMapping.Enabled)
				{
					cssMappingList.Add(cssMapping);
				}
			}
		}
    }
}